package org.mainlove.project.web.framework;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.mainlove.project.web.framework.annotation.Service;
import org.mainlove.project.web.framework.model.MethodConfig;
import org.mainlove.project.web.framework.model.ServiceConfig;

public class ActionRepository {

	private static final String ScanPath = "org/mainlove/project/web/web/service";
	private static Map<String, ServiceConfig> actionConfigMap;

	private ActionRepository() {
	}

	public static Map<String, ServiceConfig> getActionConfigMap() {

		if (actionConfigMap == null) {
			actionConfigMap = new HashMap<String, ServiceConfig>();
		}

		return actionConfigMap;

	}

	public static void initActionConfigMap(String rootPath) {

		try {

			File rootDirectory = new File(rootPath + ScanPath);

			File[] classFile = rootDirectory.listFiles();
			for (int i = 0; i < classFile.length; i++) {
				File file = classFile[i];
				String className = file
						.getPath()
						.substring(
								file.getPath().indexOf(rootPath.replace("/", "\\"))
										+ rootPath.length()).replace("\\", ".");

				className = className.substring(0, className.lastIndexOf("."));

				Class<?> c = Class.forName(className);

				Service service = c.getAnnotation(Service.class);

				if (service != null) {

					ServiceConfig serviceConfig = new ServiceConfig();
					serviceConfig.setServiceClassName(className);
					serviceConfig
							.setServiceName(c.getSimpleName().replace(c.getSimpleName().charAt(0),
									(char) (c.getSimpleName().charAt(0) + 32)));
					addMethodConfig(serviceConfig, c.getMethods());
					getActionConfigMap().put(service.name(), serviceConfig);

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void addMethodConfig(ServiceConfig serviceConfig, Method[] methods) {

		for (Method method : methods) {
			org.mainlove.project.web.framework.annotation.Method methodConfigs = method
					.getAnnotation(org.mainlove.project.web.framework.annotation.Method.class);

			if (methodConfigs != null) {
				MethodConfig methodConfig = new MethodConfig();
				methodConfig.setName(methodConfigs.name());
				methodConfig.setMethodName(method.getName());
				methodConfig.setMethodWay(methodConfigs.method().toString());
				serviceConfig.getMethod().add(methodConfig);
			}
		}
	}

	public static void main(String[] args) {

		String rootPath = ActionRepository.class.getResource("/").getPath().substring(1);

		initActionConfigMap(rootPath);

		System.out.println(getActionConfigMap());
	}

}
